import { constantRoutes, asyncRoutes } from '@/router'

/**
 * 判断用户是否有此权限
 * @param roles
 * @param route
 */

function hasPermission(roles, route) {
  // 如果route包含meta且含有roles属性
  if (route.meta && route.meta.roles) {
    // 遍历用户的roles，如果用户的某个role命中此路由的roles，将拥有对应权限
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    // 如果route没有meta，默认有权限
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */

export function filterAsyncRoutes(routes, roles) {
  // console.log(routes)
  const res = []
  // 首先遍历routes
  // routes.forEach(route => {
  //   // 浅拷贝route
  //   const tmp = { ...route }
  //   // 验证此路由是否有访问权限
  //   if (hasPermission(roles, tmp)) {
  //     // 如果有权限，则判断是否有children
  //     if (tmp.children) {
  //       // 如果有权限，则遍历children，过滤出有权限的children
  //       tmp.children = filterAsyncRoutes(tmp.children, roles)
  //     }
  //     // 将过滤出来的有权限的路由放到res数组中
  //     res.push(tmp)
  //   }
  // })
  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })
  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    // 保存动态路由
    state.addRoutes = routes
    // 合并路由
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit }, roles) {
    return new Promise(resolve => {
      let accessRoutes
      // 首先判断是否包含admin，只要包含admin，就直接将asyncRoutes复制给accessRoutes
      if (roles.includes('admin')) {
        accessRoutes = asyncRoutes || []
      } else {
        // 如果不是admin,执行filterAsyncRoutes
        accessRoutes = filterAsyncRoutes(asyncRoutes, roles)
      }
      // 执行SET_ROUTES，将accessRoutes赋值给addRoutes,将accessRoutes和原来的constantRoutes合并
      commit('SET_ROUTES', accessRoutes)
      resolve(accessRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
